﻿using System;
using mb;

[assembly : Xamarin.Forms.ResolutionGroupName("com.jj")]

[assembly : Xamarin.Forms.ExportEffect(typeof(AndroidPressedEffect), "PressedEffect")]
public class AndroidPressedEffect : Xamarin.Forms.Platform.Android.PlatformEffect
{
    private bool _attached;
    public static void Initialize() { }
    public AndroidPressedEffect() { }
    protected override void OnAttached()
    {
        //because an effect can be detached immediately after attached (happens in listview), only attach the handler one time.
        if (!_attached)
        {
            // mb.App.logger.Log("onattach", Control, Container, Element);
            if (Control != null)
            {
                Control.LongClickable = true;
                Control.LongClick += Control_LongClick;
                Control.Clickable = true;
                Control.Click += Control_Click;
            }
            else
            {
                Container.LongClickable = true;
                Container.LongClick += Control_LongClick;
                Container.Clickable = true;
                Container.Click += Control_Click;
            }
            _attached = true;
        }
    }

    protected override void OnDetached()
    {
        if (_attached)
        {
            if (Control != null)
            {
                Control.LongClickable = false;
                Control.LongClick -= Control_LongClick;
                Control.Clickable = false;
                Control.Click -= Control_Click;
            }
            else
            {
                Container.LongClickable = false;
                Container.LongClick -= Control_LongClick;
                Container.Clickable = false;
                Container.Click -= Control_Click;
            }
            _attached = false;
        }
    }

    private void Control_Click(object sender, EventArgs e)
    {
        Console.WriteLine("Invoking press command");
        var command = PressedEffect.GetCommand(Element);
        command?.Execute(Element);
    }
    private void Control_LongClick(object sender, Android.Views.View.LongClickEventArgs e)
    {
        Console.WriteLine("Invoking long press command");
        var command = PressedEffect.GetLongPressCommand(Element);
        command?.Execute(Element);
    }

}